package com.muqi.app.qlearn.fragments;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.easemob.easeui.widget.CircularImage;
import com.muqi.app.network.http.GlideImageUtils;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.adapter.TreeAdapter;
import com.muqi.app.qlearn.adapter.TreeAdapter.OnTreeLeftClick;
import com.muqi.app.qlearn.adapter.TreeAdapter.OnTreeRightClick;
import com.muqi.app.qlearn.modles.GrowTreeInfo;
import com.muqi.app.qlearn.modles.TreeInfo;
import com.muqi.app.qlearn.publish.RecordDetailActivity;
import com.muqi.app.qlearn.student.BaseChildFragment;
import com.muqi.app.qlearn.student.MenuActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.GrowRecordActivity;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.db.MyClassStudent;
import com.muqi.app.user.widget.ClassWithStudentsWindow;
import com.muqi.app.widget.pulltorefresh.XListView;

public class TabFileTree extends BaseChildFragment implements OnClickListener,
		XListView.IXListViewListener, OnTreeLeftClick, OnTreeRightClick,
		ClassWithStudentsWindow.SelectCWithSListener {
	private ImageButton changeButton;
	private CircularImage userAvatar;
	private TextView ftTitle;
	private View lv_head_view;
	private XListView lv_trees;
	private TreeAdapter treeAdapter;
	private ArrayList<ArrayList<TreeInfo>> trArrayList;
	private int page = 1;
	private TreeRefreshReceiver receiver = null;
	private ClassWithStudentsWindow myStudentsWindow = null;

	/**
	 * 用来实现加载对应的下一页的数据 默认加载学生的
	 */
	private int type = 0;
	private String student_id;
	private ImageView mIvBottom;

	private String url;
	private String record_type;
	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if(getActivity() instanceof GrowRecordActivity){
			url=NetWorkApi.GET_GROWRECORD_TYPE_API;
			record_type=((GrowRecordActivity)getActivity()).type;
		}else{
			url=NetWorkApi.GET_GROWTRESS_LIST;
		}
	}

	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View fileView = inflater.inflate(R.layout.fragment_files_tree, null);
		ftTitle = (TextView) fileView.findViewById(R.id.ft_title);
		mIvBottom = (ImageView) fileView.findViewById(R.id.iv_tree_buttom);
		lv_head_view = inflater.inflate(R.layout.item_tree_head, null);
		return fileView;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initView(view);
		initListener();

		loadData(mSpUtil.getCurrentChildId());

	}

	private void loadData(final String studentID) {
		showLoading();
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("class_manager_id", mSpUtil.getChildClassId());
		sendMap.put("student_id", studentID);
		sendMap.put("page", page);
		sendMap.put("type", record_type);
		String requestUrl = ParamsUtils.buildParams(
				url, sendMap);
		MyAsyncHttp.get(getActivity(), requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				hideLoading();
				lv_trees.stopRefresh();
				lv_trees.stopLoadMore();
				if (resuleCode == RESULTCODE.SUCCESS) {

					int jsonType = 1;
					if (!studentID.equals("0")) {
						jsonType = 2;
					}
					GrowTreeInfo info = ResponseUtils.getFileTreeLists(
							getActivity(), result, jsonType);
					if (info != null) {

						if (info.studentInfo != null) {
							displayStudentData(info.studentInfo.avatarInfo.fileurl_02);
						}

						if (jsonType == 1 && info.classInfo != null) {
							GlideImageUtils.setImageLoader(getActivity(),
									info.classInfo.class_avatr, userAvatar,
									R.drawable.tree_class_default);
						} else if (info.studentInfo != null) {
							displayStudentData(info.studentInfo.avatarInfo.fileurl_02);
						}

						displayTreeDetail(info.getDetail());
						if (info.getDetail() != null) {
							if (info.getDetail().size() < 10) { // 动态显示是否加载更多数据
								lv_trees.setPullLoadEnable(false);
							} else {
								page++;
								lv_trees.setPullLoadEnable(true);
							}
						}
					}
				} else {
					ShowToast.showShort(mActivity, result);
				}
			}

		});
	}

	/**
	 * 展示学生的信息
	 * 
	 * @param studentInfo
	 */

	protected void displayStudentData(String ava) {
		if (ava != null) {
			GlideImageUtils.setAvatar(getActivity(), ava, userAvatar);
		}
	}

	/**
	 * 展示成长树的信息
	 * 
	 * @param detail
	 */
	protected void displayTreeDetail(ArrayList<TreeInfo> detail) {
		ArrayList<ArrayList<TreeInfo>> lists = null;
		ArrayList<TreeInfo> treeInfos = null;
		int currentPosition = 0;

		if (detail != null) {
			lists = new ArrayList<ArrayList<TreeInfo>>();
			int count = detail.size() % 2 == 0 ? detail.size() / 2 : detail
					.size() / 2 + 1;
			if (detail.size() <= 2) {

				switch (detail.size()) {
				case 0:
					if (page == 1) {
						treeInfos = new ArrayList<TreeInfo>();
						treeInfos.add(null);
						treeInfos.add(null);
						lists.add(treeInfos);
					}

					break;
				case 1:
					treeInfos = new ArrayList<TreeInfo>();
					treeInfos.add(detail.get(0));
					treeInfos.add(null);
					lists.add(treeInfos);
					break;
				case 2:
					treeInfos = new ArrayList<TreeInfo>();
					treeInfos.add(detail.get(0));
					treeInfos.add(detail.get(1));
					lists.add(treeInfos);
					break;
				}
				if (page == 1) {
					treeInfos = new ArrayList<TreeInfo>();
					treeInfos.add(null);
					treeInfos.add(null);
					lists.add(treeInfos);
				}

			} else {
				for (int i = 0; i < count - 1; i++) {
					treeInfos = new ArrayList<TreeInfo>();
					treeInfos.add(detail.get(currentPosition++));
					treeInfos.add(detail.get(currentPosition++));
					lists.add(treeInfos);
				}
				if (detail.size() % 2 == 0) {
					treeInfos = new ArrayList<TreeInfo>();
					treeInfos.add(detail.get(currentPosition++));
					treeInfos.add(detail.get(currentPosition));
					lists.add(treeInfos);
				} else {
					treeInfos = new ArrayList<TreeInfo>();
					treeInfos.add(detail.get(currentPosition++));
					treeInfos.add(null);
					lists.add(treeInfos);
				}
			}

		}
		// 更新界面数据
		Log.e("===", detail.size() + " " + lists + "  " + trArrayList);
		if (page == 1) {
			trArrayList = lists;
			treeAdapter = new TreeAdapter(trArrayList, mActivity);
			treeAdapter.setLeftClick(this);
			treeAdapter.setRightClik(this);
			lv_trees.setAdapter(treeAdapter);
		} else {
			for (int i = 0; i < lists.size(); i++) {
				trArrayList.add(lists.get(i));
			}
			treeAdapter.notifyDataSetChanged();
		}

	}

	private void initListener() {
		changeButton.setOnClickListener(this);
		userAvatar.setOnClickListener(this);
		treeAdapter.setLeftClick(this);
		treeAdapter.setRightClik(this);
		lv_trees.setXListViewListener(this);
	}

	private void initView(View view) {
		/*
		 * if (!(mActivity instanceof MenuActivity)) {
		 * mIvBottom.setVisibility(View.GONE); }
		 */
		userAvatar = (CircularImage) lv_head_view
				.findViewById(R.id.user_circularImage);
		changeButton = (ImageButton) view.findViewById(R.id.changeImageButton);
		lv_trees = (XListView) view.findViewById(R.id.lv_tree);
		lv_trees.addHeaderView(lv_head_view);
		lv_trees.setPullLoadEnable(false);
		lv_trees.setPullRefreshEnable(false);
		trArrayList = new ArrayList<ArrayList<TreeInfo>>();
		treeAdapter = new TreeAdapter(trArrayList, getActivity());
		lv_trees.setAdapter(treeAdapter);

		if (currentChild != null) {
			initChildrenDatas(currentChild);
			setMyclassStudentsWindow(currentChild);
		}

		receiver = new TreeRefreshReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MContants.REFRESH_FILETREE_ACTION);
		filter.addAction(MContants.CHANGE_CURRENT_CHILD_ACTION);
		getActivity().registerReceiver(receiver, filter);
		student_id = mSpUtil.getCurrentChildId();
	}

	private void initChildrenDatas(ChildBean myChild) {
		ftTitle.setOnClickListener(this);
		Glide.with(this).load(myChild.avatar_02)
				.placeholder(R.drawable.default_avator).into(userAvatar);
		ftTitle.setText(myChild.name + "");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.changeImageButton:
			/*
			 * if (parentAct != null) { parentAct.changeTreeFragment(false); }
			 */
			break;
		case R.id.user_circularImage:

			break;
		case R.id.ft_title:
			if (myStudentsWindow != null) {
				myStudentsWindow.showPopupWindow(v);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onRefresh() {
		page = 1;
		if (type == 1) {
			loadData("0");
		} else {
			loadData(student_id);
		}
	}

	@Override
	public void onLoadMore() {

		if (type == 1) {
			loadData("0");
		} else {
			loadData(student_id);
		}
	}

	@Override
	public void onRightClick(int position) {
		TreeInfo info = trArrayList.get(position).get(1);
		if (info != null) {
			toRecordDetail(info);
		}
	}

	@Override
	public void onLeftClick(int position) {

		TreeInfo info = trArrayList.get(position).get(0);
		if (info != null) {
			toRecordDetail(info);
		}

	}

	/**
	 * 进入到记录的详细界面
	 */
	private void toRecordDetail(TreeInfo info) {
		Intent intent = new Intent(getActivity(), RecordDetailActivity.class);
		intent.putExtra(RecordDetailActivity.RECORD_ID, info.getId());
		startActivity(intent);
	}

	/**
	 * 为了实现界面的切换
	 * 
	 * @author smile_x
	 * 
	 */
	class TreeRefreshReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(MContants.REFRESH_FILETREE_ACTION)) {
				onRefresh();
			} else if (intent.getAction().equals(
					MContants.CHANGE_CURRENT_CHILD_ACTION)) {
				student_id = mSpUtil.getCurrentChildId();
				onRefresh();
				ChildBean myChild = (ChildBean) intent
						.getSerializableExtra(MContants.CHANGE_CURRENT_CHILD_DATAS);
				ftTitle.setText(myChild.name + "");
				Glide.with(mActivity).load(myChild.avatar_02)
						.placeholder(R.drawable.default_avator)
						.into(userAvatar);
				setMyclassStudentsWindow(myChild);
			}
		}
	}

	private void setMyclassStudentsWindow(ChildBean myChild) {
		myStudentsWindow = null;
		List<MyClassStudent> dbStudents = cupboard().withDatabase(sqlDb)
				.query(MyClassStudent.class)
				.withSelection("class_id = ?", mSpUtil.getChildClassId())
				.list();
		myStudentsWindow = new ClassWithStudentsWindow(getActivity(), myChild,
				dbStudents, this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(receiver);
	}

	@Override
	protected void onChoiceChildResult(ChildBean myChild) {
		initChildrenDatas(myChild);
	}

	@Override
	public void onSelectResult(int type, String className,
			MyClassStudent selected) {
		this.type = type;
		page = 1;
		if (type == 1) {
			ftTitle.setText(className);
			refreshFileView("0");
		} else {
			this.student_id = selected.student_id;
			ftTitle.setText(selected.student_name + "");
			refreshFileView(selected.student_id);
		}
	}

	private void refreshFileView(String studentId) {

		page = 1;
		loadData(studentId);
	}

}
